package com.flyme.module.file.provider.listener;

import com.aliyun.vod.upload.resp.UploadVideoResponse;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.module.file.client.entity.SysCataLog;
import com.flyme.module.file.client.entity.SysFile;
import com.flyme.module.file.client.event.CourseUploadEvent;
import com.flyme.module.file.provider.service.SysCataLogService;
import com.flyme.module.file.provider.service.SysFileService;
import com.flyme.module.file.provider.service.impl.SysCataLogServiceImpl;
import com.flyme.module.file.provider.utils.AliVodUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class CourseUploadListener implements SmartApplicationListener {
	

	@Autowired
	private SysCataLogService cataLogService;
	@Autowired
	private SysFileService fileService;
	/**
	 * 只有监听类型匹配才执行
	 */
	@Override
	public boolean supportsEventType(Class<? extends ApplicationEvent> eventClass) {
		return eventClass == CourseUploadEvent.class;
	}

	/**
	 * 只有在SysCourseServiceImpl内发布的事件时才会执行下面逻辑
	 */
	@Override
	public boolean supportsSourceType(Class<?> aClass) {
		return aClass == SysCataLogServiceImpl.class;
	}

	/**
	 * 业务逻辑
	 */
	@Override
	@Async
	public void onApplicationEvent(ApplicationEvent applicationEvent) {

		// 转换事件类型
		CourseUploadEvent userRegisterEvent = (CourseUploadEvent) applicationEvent;
		// 获取注册用户对象信息
		SysCataLog cataLog = userRegisterEvent.getCataLog();
		String fileId=cataLog.getFileId();
		SysFile file=fileService.getById(fileId);
		if(ObjectUtils.isNotEmpty(file)){
			UploadVideoResponse response = AliVodUtil.uploadVideo(file.getFileName(), file.getLocalPath());
			String videoId=response.getVideoId();
			UpdateWrapper up=new UpdateWrapper<SysCataLog>();
			up.set(true,"videoId",videoId).eq(true,"id",cataLog.getId());
			cataLogService.update(up);
		}
	}
	/**
	 * 同步情况下监听执行的顺序
	 */
	@Override
	public int getOrder() {
		return 0;
	}
}
